#include <iostream>
#include <cstdlib>
using namespace std;

#include "tree.h"
#include "bomloader.h"
#include "columnnames.h"

extern uint maxAmong(uint n_args, ...);
extern int maxDepth;

void usage()
{
    cout<<" Usage: bomtree bom_file bom_comp_file [item_id1, item_id2] "<<endl;
    cout<<" If the default indexes won't work, please provide ColumnNames folder under current directory "<<endl;
    cout<<" If item_id given, we will only print trees related with these items and this may be faster"<<endl;
    cout<<" yanhan.tang@oracle.com [2014 Aug 7th] "<<endl;
    cout<<" Become of us, become of you "<<endl;
}

int main(int argc, char** argv)
{
    /// Just for test
#if 0
    ItemOrg *io = new ItemOrg(502944, 1025164);

    unsigned int key = io->key();
    cout<<"size of int: "<<sizeof(int)<<endl;
    cout<<"Key: "<<key<<endl;

    uint maxOne = maxAmong(8,8, 2, 0, 4, 3,1,2,10);
    cout<<"Max = "<<maxOne<<endl;

#endif

    if( argc < 2 )
    {
        usage();
        exit(0);
    }

    BomLoader loader;

    // Column Index with default values
    uint bomIdx_bomSeqId = 8, bomIdx_assyId = 2, bomIdx_assyOrgId = 0,
    bomCompIdx_bomSeqId = 4, bomCompIdx_assyId = 3,
    bomCompIdx_itemId = 1, bomCompIdx_orgId = 2, bomCompIdx_usage = 10;

    // Try to load column names from ColumnNames directory
    ColumnNames colNames;
    if ( colNames.loadColumnNames("MSLD_BOM.dat") )
    {
        bomIdx_bomSeqId  = colNames.getIndex("bill_sequence_id");
        bomIdx_assyId    = colNames.getIndex("assembly_item_id");
        bomIdx_assyOrgId = colNames.getIndex("organization_id");
    }

    if ( colNames.loadColumnNames("MSLD_BOM_COMP.dat") )
    {
        bomCompIdx_bomSeqId = colNames.getIndex("bill_sequence_id");
        bomCompIdx_assyId   = colNames.getIndex("using_assembly_id");
        bomCompIdx_itemId   = colNames.getIndex("inventory_item_id");
        bomCompIdx_orgId    = colNames.getIndex("organization_id");
        bomCompIdx_usage    = colNames.getIndex("usage_quantity");
    }

    loader.loadBomRecords( argv[1],argv[2],
                          bomIdx_bomSeqId, bomIdx_assyId, bomIdx_assyOrgId,
                          bomCompIdx_bomSeqId,
                          bomCompIdx_assyId,
                          bomCompIdx_itemId, bomCompIdx_orgId,
                          bomCompIdx_usage);

    vector<int> itemIds;
    if( argc > 2 )
    {
        for( int i=3; i<argc; i++ )
        {
            int itemId = atoi(argv[i]);
            itemIds.push_back(itemId);
        }
    }

    loader.filterBomRecords(itemIds);
    loader.createBoms();
    loader.printBoms();

    cout<<"\tTree Max Depth: "<<maxDepth<<endl;
    return 0;
}

